package com.controller.sys;

import com.common.Result;
import com.common.log.OperationLog;
import com.common.log.OperationType;
import com.entity.sys.User;
import com.service.sys.UserService;
import com.vo.sys.UserLoginParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 用户登陆
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    @OperationLog(operationType = OperationType.LOGIN, describe = "用户登录", entity = UserLoginParam.class, primaryKey = "")
    public Result login(@RequestBody UserLoginParam userLoginParam, HttpServletRequest request) {
        System.out.println("userLoginParam = " + userLoginParam);
        return userService.login(userLoginParam, request);
    }

    /**
     * 主要通知前端删除浏览器中的token
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.success("注销成功!");
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/user/info")
    public Result getUserInfo(Principal principal) {
        if (null == principal) {
            return Result.fail("获取到当前登录用户信息");
        }
        String username = principal.getName();
        User user = userService.getUserByUsername(username);
        user.setPassword(null); //配置密码为空，只能在这里配置，不能再service配置，应该登录需要校验密码
        //返回用户信息包含角色
        user.setRoles(userService.getRoles(user.getId()));
        return Result.success(user);
    }

}
